package com.shanghaionstar.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Toast;

import com.onstar.cn.SharedPoiItemInfo;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.result.PollingResult;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.iview.IMainTabView;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.discover.DiscoverFragment;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.HomeFragment;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.notification.bean.NotificationConstants;
import com.shanghaionstar.notification.service.NotificationControl;
import com.shanghaionstar.presenter.MainTabPresenter;
import com.shanghaionstar.remote.RemoteFailDialog;
import com.shanghaionstar.remote.RemoteFragment;
import com.shanghaionstar.user.BroadcastFragment;
import com.shanghaionstar.user.MoreFragment;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.AppStoreUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.utils.NavHolder;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;

import rx.Subscription;
import rx.functions.Action1;


/**
 * Created by 7828wc on 2016/6/22.
 */
@ContentView(R.layout.main)
public class MainTabActivity extends BaseActivity implements IMainTabView {

    @Override
    public void setLoading(boolean isLoading) {
    }

    @Override
    public void onResponseError(OnStarException e) {
    }

    @Override
    public void onReponseSuccess(Object object) {
    }

    @Override
    public Activity onActivity() {
        return null;
    }

    private TabLayout.Tab tab_home, tab_remote, tab_discover, tab_user;

    @FindViewById
    private TabLayout tablayout;

    @FindViewById
    private ViewPager view_pager;
    private String[] titles;
    private Subscription vehicleSubscription;
    private Context applicationContext;
    private MainTabPresenter mainTabPresenter;
    private HomeFragment mHomeFragment;
    private MoreFragment mMoreFragment;
    private RemoteFragment mRemoteFragment;
    private DiscoverFragment disconverFragment;
    public String receiveType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusinessUtil.loadConfig(this);
        applicationContext = getApplicationContext();
        titles = getResources().getStringArray(R.array.tab_name);
        mainTabPresenter = new MainTabPresenter(getScheduler(), this);
        mainTabPresenter.setView(this);

        initView();
        initEvents();
        /**
         * 开启定位服务
         */
        requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, new PermissionCall() {
            @Override
            public void requestSuccess() {
                beginLocate();
            }

            @Override
            public void refused() {
                Toast.makeText(MainTabActivity.this, "please open the location permission", Toast.LENGTH_SHORT).show();
            }
        });
//        beginLocate();

        registAllPageAlert();

        /**
         * 注册网络监听广播
         */
        mainTabPresenter.initConnectBroad();

        mainTabPresenter.checkNewVersion();
        mainTabPresenter.initBroadcastUtil();
        saveDeviceInfo();
        loadXG();
    }

    private void saveDeviceInfo() {
        NotificationControl.getInstants(this).saveDeviceInfo(true);
    }

    private void loadXG() {
        // 开启logcat输出，方便debug，发布时请关闭
        XGPushConfig.enableDebug(getApplicationContext(), true);

        XGPushManager.registerPush(getApplicationContext(), new XGIOperateCallback() {
            /**
             * 操作成功时的回调。
             *
             * @param data
             *            操作成功的业务数据，如注册成功时的token信息等。
             * @param flag
             *            标记码
             */
            @Override
            public void onSuccess(Object data, int flag) {
                LogManager.getInstance(getBaseContext()).d("注册成功，设备token为：" + data);
            }

            /**
             * 操作失败时的回调
             *
             * @param data
             *            操作失败的业务数据
             * @param errCode
             *            错误码
             * @param msg
             *            错误信息
             */
            @Override
            public void onFail(Object data, int errCode, String msg) {
                LogManager.getInstance(getBaseContext()).d("注册失败，错误码：" + errCode + ",错误信息：" + msg);
            }
        });

//        String token = XGPushConfig.getToken(this);
//        LogManager.getInstance().d("the xg token is-------->>"+token);

    }

    @Override
    protected void onResume() {
        super.onResume();
        loadBroadcasts();
        dispatchPartnerEvent(getIntent());
    }

    public void showMark() {
        if (mMoreFragment != null)
            mMoreFragment.showRedMark();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String flag = intent.getExtras().getString("from");
        if ("remote".equals(flag)) {
            //消息列表切换到远程tab
            tab_remote.select();
            view_pager.setCurrentItem(1);
        } else {
            setIntent(intent);
            dispatchPartnerEvent(intent);
        }
    }

    /**
     * 分发处理第三方数据：
     * 由于maintabactivity设置为singleInstance模式，所以除了第一次在onresume中可以接收到intent参数，往后只能在onNewIntent接收
     * 此处设置getIntent().putExtra(Constants.PARTNER_3RD_FLAG, "");可以避免onResume中的重复分发
     */
    private void dispatchPartnerEvent(Intent intent) {
        // 从推送消息进入APP
        if (!CommonUtil.isNull(getIntent().getStringExtra("receiveType"))) {
            String receiveType = getIntent().getStringExtra("receiveType");
            if (receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_URL)) {
                //消息是link的时候
//                Intent intentWeb = new Intent(this, CommonWebViewActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("topTitle", getIntent().getStringExtra("title"));
//                bundle.putString("linkUrl", getIntent().getStringExtra("uri"));
//                intentWeb.putExtras(bundle);
//                startActivity(intentWeb);
                WebDataEntity entity = new WebDataEntity();
                entity.setTopTitle(getIntent().getStringExtra("title"));
                entity.setLinkUrl(getIntent().getStringExtra("uri"));
                CommonWebViewActivity.launchCommonWeb(this, entity);
            } else if (receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_BROADCAST)) {
                //广播中心
                new LoginUtil().loginAndActionCallBack(this, RxConstants.MORE_PAGE, new ILoginListener() {
                    @Override
                    public void onLogin(Bundle bundle, String resultCode) {
                        Intent it = new Intent(MainTabActivity.this, MoreActivity.class);
                        it.putExtra(FinalConstants.JUMP_FLAG, BroadcastFragment.class.getName());
                        startActivity(it);
                    }
                }, null);
            } else if (receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_OVD)) {
                //消息是ovd的直接跳转ovd车况检测报告页面
                dispatchOVD("OVDEmailFragment");
            } else if (receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_DRIVINGSCORE)) {
                if (ApplicationUtil.getInstance().isLogin()) {
                    //跳转驾驶评分页面
                    WebDataEntity entity = new WebDataEntity();
                    entity.setTopTitle(getIntent().getStringExtra("title"));
                    entity.setLinkUrl(getIntent().getStringExtra("uri"));
//                    mHomeFragment.setDriveScoreEntity(entity);
                    entity.setCanGoBack(true);
                    CommonWebViewActivity.launchCommonWeb(MainTabActivity.this, entity);
                } else {
                    this.receiveType = receiveType;
                }
            } else if (receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_REMOTE)) {
                ApplicationUtil.getInstance().setAuthorized(true);
                view_pager.setCurrentItem(1);
            } else if (receiveType.equalsIgnoreCase(NotificationConstants.B2C_RECEIVETYPE_HOME)) {
                ApplicationUtil.getInstance().setAuthorized(false);
                view_pager.setCurrentItem(0);
            } else if (receiveType.equalsIgnoreCase("100")) {
                if (ApplicationUtil.getInstance().isLogin()) {
                    String url = getIntent().getStringExtra("uri");
                    WebDataEntity entity = new WebDataEntity();
                    entity.setLinkUrl(url);
                    entity.setCanGoBack(true);
                    CommonWebViewActivity.launchCommonWeb(MainTabActivity.this, entity);
                } else {
                    this.receiveType = receiveType;
                }
            }
            //因为Activity为singleTask模式，需清空一下intent中的值
            getIntent().putExtra("receiveType", "");
        }
        //第三方应用启动APP，1:显示ovd车况检测报告；2:跳转地图页面，显示POI
        String share3RDFlag = intent.getStringExtra(Constants.PARTNER_3RD_FLAG);
        if (!CommonUtil.isNull(share3RDFlag)) {
            if ("OVDEmailFragment".equals(share3RDFlag)) {
                dispatchOVD(share3RDFlag);
            } else if ("sharePOI".equals(share3RDFlag)) {
                dispatchAMapPoi(intent);
            }
            getIntent().putExtra(Constants.PARTNER_3RD_FLAG, "");
        }
    }

    private void dispatchAMapPoi(Intent intent) {
        SharedPoiItemInfo poiItemInfo = (SharedPoiItemInfo) intent.getSerializableExtra(Constants.PARTNER_3RD_POI);
        if (mHomeFragment != null && poiItemInfo != null) {
            Bundle bundle = new Bundle();
            bundle.putString(Constants.PARTNER_3RD_FLAG, "sharePOI");
            bundle.putSerializable(Constants.PARTNER_3RD_POI, poiItemInfo);
            mHomeFragment.setArgument(bundle);
        }
    }

    private void dispatchOVD(String share3RDFlag) {
        tab_discover.select();
        view_pager.setCurrentItem(2);
        if (disconverFragment != null) {
            Bundle bundle = new Bundle();
            bundle.putString(Constants.PARTNER_3RD_FLAG, share3RDFlag);
            disconverFragment.setArgument(bundle);
            disconverFragment.performClick(share3RDFlag);
        }
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    private void initView() {
        view_pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return mHomeFragment;
                    case 1:
                        return mRemoteFragment = new RemoteFragment();
                    case 2:
                        return disconverFragment;
                    case 3:
                        return mMoreFragment = new MoreFragment();
                }
                return new HomeFragment();
            }

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });


        view_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 1) {
                    if (mRemoteFragment != null)
                        mRemoteFragment.onPageSelected();
                } else if (position == 3) {
                    if (mMoreFragment != null)
                        mMoreFragment.showHis();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        tablayout.setupWithViewPager(view_pager);
        tab_home = tablayout.getTabAt(0);
        tab_remote = tablayout.getTabAt(1);
        tab_discover = tablayout.getTabAt(2);
        tab_user = tablayout.getTabAt(3);
        disconverFragment = new DiscoverFragment();
        mHomeFragment = new HomeFragment();
        /**
         * home tab默认选中
         */
        tab_home.setIcon(R.drawable.tab_home_check);
        tab_remote.setIcon(R.drawable.tab_remote);
        tab_discover.setIcon(R.drawable.tab_discover);
        tab_user.setIcon(R.drawable.tab_my);


    }

    private void initEvents() {
        view_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                BusinessUtil.sendReportByClickType(MainTabActivity.this, FunctionNameFindId.Home_Homepage.getStringValue());
                            }
                        }).start();
                        break;
                    case 1:
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                BusinessUtil.sendReportByClickType(MainTabActivity.this, FunctionNameFindId.Home_RemoteControl.getStringValue());
                            }
                        }).start();
                        break;
                    case 2:
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                BusinessUtil.sendReportByClickType(MainTabActivity.this, FunctionNameFindId.Home_Find.getStringValue());
                            }
                        }).start();
                        break;
                    case 3:
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                BusinessUtil.sendReportByClickType(MainTabActivity.this, FunctionNameFindId.Home_Me.getStringValue());
                            }
                        }).start();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        tablayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == tab_home) {
                    tab_home.setIcon(R.drawable.tab_home_check);
                    view_pager.setCurrentItem(0);
                } else if (tab == tab_remote) {
                    tab_remote.setIcon(R.drawable.tab_remote_check);
                    view_pager.setCurrentItem(1);
                } else if (tab == tab_discover) {
                    tab_discover.setIcon(R.drawable.tab_discover_check);
                    view_pager.setCurrentItem(2);
                } else if (tab == tab_user) {
                    tab_user.setIcon(R.drawable.tab_my_check);
                    view_pager.setCurrentItem(3);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab == tab_home) {
                    tab_home.setIcon(R.drawable.tab_home);
                } else if (tab == tab_remote) {
                    tab_remote.setIcon(R.drawable.tab_remote);
                } else if (tab == tab_discover) {
                    tab_discover.setIcon(R.drawable.tab_discover);
                } else if (tab == tab_user) {
                    tab_user.setIcon(R.drawable.tab_my);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void loadBroadcasts() {
        mainTabPresenter.loadBroadcasts();
    }

    @Override
    public void onBackPressed() {
        AlertDialogUtil.showExitDialog(this);
    }

//    private Intent locateIntent;

    private void beginLocate() {
        NavHolder.getInstance(getApplicationContext()).findMyLocation();
//        locateIntent = new Intent(this, NavLocateService.class);
//        startService(locateIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mPollingRx);
        RxSubscriptions.remove(mLoginOutRx);
        RxSubscriptions.remove(mHighPraiseRx);
        mainTabPresenter.onActivityFinish();
        mainTabPresenter = null;
//        stopService(locateIntent);
    }

//    /**
//     * 注册广播以接受车辆位置
//     */
//    private void registVehicleLocation() {
//        vehicleSubscription = RxBus.getDefault()
//                .toObserverable(RxConstants.VEHICLE_LOCATE, PollingResult.class)
//                .subscribeOn(getScheduler().backgroundThread())
//                .observeOn(getScheduler().mainThread()).subscribe(new Action1<PollingResult>() {
//                    @Override
//                    public void call(final PollingResult pollingResult) {
//
//                    }
//                });
//    }

    public void remoteControlFromShortcut(int pos) {
        tab_remote.select();
        view_pager.setCurrentItem(1);
        mRemoteFragment.remotePerform(pos);
    }

    private Subscription mPollingRx, mLoginOutRx, mHighPraiseRx;

    public void registAllPageAlert() {
        mPollingRx = RxBus.getDefault().toObserverable(RxConstants.ALL_PAGE_ALERT, PollingResult.class)
                .subscribeOn(getScheduler().backgroundThread())
                .observeOn(getScheduler().mainThread()).subscribe(new Action1<PollingResult>() {
                    @Override
                    public void call(PollingResult pollingResult) {
                        RemoteCommandsType remotecommandType = RemoteCommandsType.fromValue(pollingResult.getRequestType());
                        if (remotecommandType == null) return;
                        switch (remotecommandType) {
                            case COMMANDS_TBT_ROUTE: //tbt or odd
                            case COMMANDS_NAV_DESTINATION:
                                mainTabPresenter.alertTBTODDDialog(pollingResult);
                                break;
                            case COMMANDS_LOCATION:
                                mainTabPresenter.vehicleLocateCallBack(pollingResult);
                                break;
                            case COMMANDS_LOCK_DOOR:
                            case COMMANDS_UNLOCK_DOOR:
                            case COMMANDS_CANCEL_START:
                            case COMMANDS_START:
                            case COMMANDS_ALERT:
                                if (!OnstarApplication.getApplication().isMroForeground())
                                    mainTabPresenter.vehicleRemoteControlCallBack(pollingResult);
                                break;
                        }
                    }
                });

        mLoginOutRx = RxBus.getDefault()
                .toObserverable(RxConstants.ALL_PAGE_REFRESH, String.class)
                .subscribeOn(new AppScheduler().backgroundThread())
                .observeOn(new AppScheduler().mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (RxConstants.LOGIN_OUT.equalsIgnoreCase(s)) {
                            if (view_pager != null) {
                                tab_home.select();
                                view_pager.setCurrentItem(0);
                            }
                        } else if (RxConstants.PACKAGE_OVERDUE.equalsIgnoreCase(s)) {
                            if (DeviceUtil.isChineseLanguage()) {
                                BusinessUtil.showOverDueBuyPackageDialog(MainTabActivity.this);
                            } else {
                                BusinessUtil.showOverdueUserDialog(MainTabActivity.this);
                            }
                        }
                    }
                });

        mHighPraiseRx = RxBus.getDefault().toObserverable(RxConstants.HIGH_PRAISE, String.class)
                .subscribeOn(getScheduler().backgroundThread())
                .observeOn(getScheduler().mainThread()).subscribe(new Action1<String>() {
                    @Override
                    public void call(String pollingResult) {
                        showAlertDialog(MainTabActivity.this);
//                AlertDialogUtil.showAlertDialog(MainTabActivity.this, R.string.dialog_warning, R.string.remote_success_diaolog_comment,
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
////                                progress_dialog = new ProgressDialog(onActivity());
////                                progress_dialog.setMessage(getString(R.string.sendingRequest_wait));
////                                JoinMeUtils.checkVisitor(MoreFragment.this);
//                                try {
//                                    CommonUtil.jumpAndroidMarket(MainTabActivity.this);
//                                } catch (Exception e) {
//                                    Intent intent = new Intent("android.intent.action.VIEW");
//                                    intent.setData(Uri.parse("http://android.myapp.com/myapp/detail.htm?apkName=com.shanghaionstar"));
//                                    startActivity(intent);
//                                } finally {
//                                    dialog.dismiss();
//                                }
//                            }
//                        }, true, R.string.btn_comment, R.string.btn_later);


                    }
                });
        RxSubscriptions.add(mPollingRx);
        RxSubscriptions.add(mLoginOutRx);
        RxSubscriptions.add(mHighPraiseRx);
    }

    /**
     * 发送tbt失败重试toast
     */
    @Override
    public void showAppFrontNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.nav_command_fail_alert), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mainTabPresenter.sendTbtOrOdd(poiItemInfo);
            }
        });
    }

    public void showAlertDialog(final Context context) {
        final PreferencesUtls utls = PreferencesUtls.getInstance(context);
        if (!utls.getBoolean(Constants.HAS_HIGH_PRAISE, false)) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
            alertDialog.setMessage(R.string.remote_success_diaolog_comment);
            alertDialog.setPositiveButton(R.string.btn_comment, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        //HTC手机特殊处理
                        if (Build.MANUFACTURER.contains("HTC")) {
                            AppStoreUtil.showDia(context);
                        } else {
                            CommonUtil.jumpAndroidMarket(MainTabActivity.this);
                        }
                        utls.putBoolean(Constants.HAS_HIGH_PRAISE, true);
                    } catch (Exception e) {
                        Intent intent = new Intent("android.intent.action.VIEW");
                        intent.setData(Uri.parse("http://android.myapp.com/myapp/detail.htm?apkName=com.shanghaionstar"));
                        startActivity(intent);
                    } finally {
                        dialog.dismiss();
                    }
                }
            });
            alertDialog.setNegativeButton(R.string.btn_later, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int count = utls.getInt(Constants.IGNORE_HIGH_PRAISE_TIMES, 0);
                    count = count + 1;
                    utls.putInt(Constants.IGNORE_HIGH_PRAISE_TIMES, count);
                    if (count >= 3) {
                        utls.putBoolean(Constants.HAS_HIGH_PRAISE, true);
                    }
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
    }


    /**
     * app在后端时候，发送tbt失败提示toast
     *
     * @param poiItemInfo
     */
    @Override
    public void showAppBackNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        ToastView toastView = new ToastView(this);
        toastView.setToastClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAppFrontNavCommandFailToast(poiItemInfo);
            }
        });
    }

    @Override
    public void showCommandLoading(boolean isShow) {
        if (isShow) {
            startActivity(new Intent(this, VehicleLoadingActivity.class));
        }
    }

    @Override
    public void showRemoteFailDialog(PollingResult pollingResult) {
        StringBuilder sb = new StringBuilder();
        if (!CommonUtil.isNull(pollingResult.getErrorInfo())) {//如果是一般错误
            sb.append(AlertDialogUtil.getResultSystemAlertDialog(this, false, RemoteCommandsType.fromValue(pollingResult.getRequestType()), pollingResult.getErrorInfo(), null));
        } else if (!CommonUtil.isNull(pollingResult.getHttpException())) {//如果是网络请求错误
            ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(this, pollingResult.getHttpException());
            sb.append(errorInfo.getMsg());
        } else {
            ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(this, pollingResult.getHttpException());
            sb.append(errorInfo.getMsg());
        }
        sb.append(getString(R.string.remote_fail_phone));
        new RemoteFailDialog(this, sb.toString()).show();
    }

    public static void startActivity(Activity activity) {
        activity.startActivity(new Intent(activity, MainTabActivity.class));
    }


}
